package controllers

import (
	"blog_api/models"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/keemi-zhou/validation"
	"strconv"
	"strings"
	"time"
)

type LabelController struct {
	BaseController
}

/**
 * IndexLabel
 * @Description: 首页标签
 * @Author: Jazk-Z
 * @receiver l
 * @param c
 */
func (l LabelController) IndexLabel(c *gin.Context) {
	where := "is_show = 1 and is_del = 0"
	field := "id, label_name"
	llist := models.LabelList(where, field)
	l.success(c, "success", llist)
	return
}

/**
 * AdminLabelList
 * @Description: 管理后台——标签列表
 * @Author: Jazk-Z
 * @receiver l
 * @param c
 */
func (l LabelController) AdminLabelList(c *gin.Context) {
	keyword := strings.TrimSpace(c.DefaultQuery("keyword", ""))
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10"))
	offset := (page - 1) * limit

	llist, count := models.AdminLabelList(limit, offset, "*", keyword)
	data := make(map[string]interface{})
	data["list"] = llist
	data["count"] = count
	l.success(c, "success", data)
	return
}

func (l LabelController) AdminLabelSwitch(c *gin.Context) {
	lid := strings.TrimSpace(c.DefaultQuery("lid", "0"))
	field := strings.TrimSpace(c.DefaultQuery("field", ""))
	value, _ := strconv.Atoi(c.DefaultQuery("value", "0"))
	valid := validation.Validation{}
	valid.Required(lid, "标签id")
	valid.Required(field, "标签字段名")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			l.error(c, err.Key, "")
			return
		}
	}

	where := fmt.Sprintf("id=%s", lid)
	data := map[string]interface{}{
		field: value,
	}
	err := models.AdminLabelUpdateField(where, data)
	if err != nil {
		l.error(c, err)
		return
	}
	l.success(c, "success", data)
	return
}

func (l LabelController) AdminLabelSave(c *gin.Context) {
	lid, _ := strconv.Atoi(c.DefaultQuery("id", "0"))
	label_name := strings.TrimSpace(c.DefaultQuery("label_name", ""))
	order, _ := strconv.Atoi(c.DefaultQuery("order", "0"))
	is_show, _ := strconv.Atoi(c.DefaultQuery("is_show", "0"))

	valid := validation.Validation{}
	valid.Required(label_name, "标签名不能为空")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			l.error(c, err.Key, "")
			return
		}
	}

	where := fmt.Sprintf("id = %v", lid)
	data := map[string]interface{}{
		"label_name": label_name,
		"order":      order,
		"is_show":    is_show,
	}
	if lid == 0 {
		data["add_time"] = time.Now().Unix()
	} else {
		data["update_time"] = time.Now().Unix()
	}
	err := models.AdminLabelCreateOrUpdate(lid, where, data)
	if err != nil {
		l.error(c, err, "")
	}
	l.success(c, "success", "")
}
